package yt.demo.appcoresystem.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yt.demo.appcommontools.utils.AssertUtils;
import yt.demo.appcoresystem.dto.LoginDTO;
import yt.demo.appcoresystem.dto.MenuTreeDTO;
import yt.demo.appcoresystem.entity.SystemUser;
import yt.demo.appcoresystem.service.IAdminAuthService;
import yt.demo.appcoresystem.service.ISystemMenuService;
import yt.demo.appcoresystem.service.ISystemUserService;
import yt.demo.appcoresystem.vo.LoginVo;
import java.util.*;

@Slf4j
@Service
public class AuthService implements IAdminAuthService {

    private final ISystemUserService userService;
    private final ISystemMenuService menuService;

    @Autowired
    public AuthService(ISystemUserService userService, ISystemMenuService menuService) {
        this.userService = userService;
        this.menuService = menuService;
    }

    public LoginVo login(LoginDTO dtd) {
        SystemUser user = this.userService.getUsernameInfo(dtd.username());
        AssertUtils.isNull(user, "用户信息不存在！");
        AssertUtils.isLeOne(user.getStatus(), "用户已被禁用！");
        String encryptPassword = this.userService.encryptPassword(dtd.password(), user.getSalt());
        AssertUtils.isFalse(user.getPassword().equals(encryptPassword), "密码错误！");
        user.setLoginTime(new Date());
        user.updateById();
        StpUtil.login(user.getId());
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        StpUtil.getTokenSession().set("user", user);
        StpUtil.getSession().set("permissionList", userService.getPermissionList(user.getId()));
        return loginData(user, tokenInfo);
    }

    private LoginVo loginData(SystemUser user, SaTokenInfo tokenInfo) {
        LoginVo loginVo = new LoginVo();
        loginVo.setUsername(user.getUsername());
        loginVo.setAvatar(user.getAvatar());
        loginVo.setAccessToken(tokenInfo.getTokenValue());
        loginVo.setRoles(List.of("admin"));
        return loginVo;
    }

    public static SystemUser getUserInfo() {
        return (SystemUser) StpUtil.getTokenSession().get("user");
    }



    public List<MenuTreeDTO> getMenu() {
        return this.menuService.getMenu();
    }

}
